﻿using System;
using System.Reflection;

namespace MvcSimplyCleverPart3
{
    public class LocalizableControllerNameAttribute : Attribute
    {
        public LocalizableControllerNameAttribute(Type resourceType, string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Cannot be empty or null", "name");
            }

            if (resourceType == null)
            {
                throw new ArgumentNullException("resourceType");
            }

            this.Name = name;
            this.ResourceType = resourceType;
        }

        public virtual string LocalizedControllerName
        {
            get
            {
                return GetPropertyValue(this.ResourceType, this.Name);
            }
        }

        public string Name { get; private set; }

        public Type ResourceType { get; private set; }

        private static string GetPropertyValue(Type type, string propertyName)
        {
            PropertyInfo propertyInfo = type.GetProperty(propertyName,
                BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
            if (propertyInfo == null)
            {
                return null;
            }

            return (string)propertyInfo.GetValue(null, new object[] { });
        }
    }
}